using System;
using System.Collections.Generic;
using System.Configuration;

namespace Tyng.Data.Utilities
{
	public sealed class DatabaseMap : System.Collections.IEnumerable, IDisposable
	{
        private const string RuntimePrefix = "DbRuntimeName";
        private const string NamePrefix = "DbMappingName";
		private const string RawPathPrefix = "DbMappingRawPath";
		private const string ScriptPathPrefix = "DbMappingScriptPath";
		private const string ConnectionStringPrefix = "DbMappingConnectionString";

		Dictionary<string, Database> _dbs;

		public DatabaseMap(Database[] dbs)
		{
            _dbs = new Dictionary<string, Database>(dbs.Length);

			for(int i = 0; i < dbs.Length; i++)
				_dbs.Add(dbs[i].Name, dbs[i]);
		}

        internal DatabaseMap(Dictionary<string, Database> dbs)
		{
			_dbs = dbs;
		}

		public Database this[string name] { get { return _dbs[name]; } }
		public int Count { get { return _dbs.Count; } }

		public bool Contains(string name) { return _dbs.ContainsKey(name); }

		public static DatabaseMap GetDatabaseMap()
		{
            Dictionary<string, Database> dbs = new Dictionary<string, Database>();
			int counter = 1;

            while (HybridSettings.GetValue(NamePrefix + counter) != null)
			{
                string runtime = HybridSettings.GetValue(RuntimePrefix + counter);
                string name = HybridSettings.GetValue(NamePrefix + counter);
                string conn = HybridSettings.GetValue(ConnectionStringPrefix + counter);
                string path = HybridSettings.GetValue(ScriptPathPrefix + counter);
                string raw = HybridSettings.GetValue(RawPathPrefix + counter);

				dbs.Add(name, new Database(runtime, name, conn, path, raw));
					
				counter++;
			}

#if OUTPUT
			Console.WriteLine("\n\nDatabase Map:");

			foreach(Database db in dbs.Values)
			{
				Console.WriteLine("Name: {0}\tPath: {1}", db.Name, db.Path);
			}

			Console.WriteLine("\n\n");
#endif
	
			return new DatabaseMap(dbs);
		}


		#region IEnumerable Members

        public System.Collections.IEnumerator GetEnumerator()
		{
			return _dbs.Values.GetEnumerator();
		}

		#endregion

		#region IDisposable Members

		public void Dispose()
		{
			if(_dbs != null)
			{
				foreach(object db in _dbs.Values)
				{
					IDisposable disposable = db as IDisposable;

					if(disposable != null)
						disposable.Dispose();
				}
			}
		}

		#endregion
	}
}
